﻿namespace HZY.Framework.DynamicApiController.Core;

/// <summary>
/// 控制器识别规则提供者
/// </summary>
public class DynamicApiControllerFeatureProvider : ControllerFeatureProvider
{
    private readonly DynamicApiControllerOptions _dynamicApiControllerOptions;

    /// <summary>
    /// 控制器识别规则提供者
    /// </summary>
    /// <param name="dynamicApiControllerOptions"></param>
    public DynamicApiControllerFeatureProvider(DynamicApiControllerOptions dynamicApiControllerOptions)
    {
        _dynamicApiControllerOptions = dynamicApiControllerOptions;
    }

    /// <summary>
    /// 是否为控制器
    /// 1、ControllerAttribute
    /// 2、DynamicApiControllerAttribute
    /// 3、继承自 IDynamicApiController 接口
    /// </summary>
    /// <param name="typeInfo"></param>
    /// <returns></returns>
    protected override bool IsController(TypeInfo typeInfo)
    {
        if (!typeInfo.IsClass)
        {
            return false;
        }

        if (typeInfo.IsAbstract)
        {
            return false;
        }

        // We only consider public top-level classes as controllers. IsPublic returns false for nested
        // classes, regardless of visibility modifiers
        if (!typeInfo.IsPublic)
        {
            return false;
        }

        if (typeInfo.ContainsGenericParameters)
        {
            return false;
        }

        if (typeInfo.IsDefined(typeof(NonControllerAttribute)))
        {
            return false;
        }

        if (
            !typeInfo.IsDefined(typeof(ControllerAttribute)) &&
            !typeInfo.IsDefined(typeof(DynamicApiControllerAttribute)) &&
            !typeof(IDynamicApiController).IsAssignableFrom(typeInfo)
            )
        {
            return false;
        }

        if (!_dynamicApiControllerOptions.ControllerTypeNameSuffixs.Any(w => typeInfo.Name.EndsWith(w, StringComparison.OrdinalIgnoreCase)))
        {
            return false;
        }

        return true;

    }



}
